import React, { useState, useEffect } from 'react';
import { Table, Button, Select, Radio, Pagination, Tabs, Space, Modal } from 'antd';
import {
  searchMessageByDepartment,
  searchMessageByLevel,
  getCompanyMessageLength,
  getSystemMessageLength,
  returnCompanyListData,
  returnSystemListData,
  firstDelete,
} from '@/api/message/index';
import MessageDialog from '../components/createEdit';
import dayjs from 'dayjs';
import { message } from 'antd';

const { TabPane } = Tabs

const MessageManagement = () => {
  // 部门
  const [department, setDepartment] = useState(null);
  // 消息级别
  const [radioValue, setRadioValue] = useState(null);
  // 公告数据
  const [companyTableData, setCompanyTableData] = useState([]);
  // 系统消息
  const [systemTableData, setSystemTableData] = useState([]);
  // 分页数据
  const [paginationData, setPaginationData] = useState({
    companyTotal: 1,
    companyPageCount: 1,
    companyCurrentPage: 1,
    systemTotal: 1,
    systemCount: 1,
    systemCurrentPage: 1,
  });
  // tabs key
  const [activeTab, setActiveTab] = useState('first');
  const [openModal, setOpenModal] = useState(false);
  const [messageData, setMessageData] = useState({});
  const [modalTitle, setModalTitle] = useState('发布公告');


  useEffect(() => {
    if (activeTab === 'first') {
      fetchCompanyMessageLength();
      fetchCompanyFirstPageList();
    } else if (activeTab === 'second') {
      fetchSystemMessageLength();
      fetchSystemFirstPageList();
    }
  }, [activeTab]);


  const fetchCompanyMessageLength = async () => {
    const res = await getCompanyMessageLength();
    setPaginationData(prev => ({
      ...prev,
      companyTotal: res.length,
      companyPageCount: Math.ceil(res.length / 10),
    }));
  };

  const fetchSystemMessageLength = async () => {
    const res = await getSystemMessageLength();
    setPaginationData(prev => ({
      ...prev,
      systemTotal: res.length,
      systemCount: Math.ceil(res.length / 10),
    }));
  };

  const fetchCompanyFirstPageList = async () => {
    const data = await returnCompanyListData(1);
    if (department) {
      setDepartment(null)
    }
    if (radioValue) {
      setRadioValue(null)
    }
    setCompanyTableData(data);
  };

  const fetchSystemFirstPageList = async () => {
    const data = await returnSystemListData(1);
    setSystemTableData(data);
  };

  const getListByDepartment = async () => {
    if (!department) return
    const data = await searchMessageByDepartment(department);
    setCompanyTableData(data);
  };

  const getMessageListByLevel = async (radioValue) => {
    const data = await searchMessageByLevel(radioValue);
    setCompanyTableData(data);
  };

  const companyCurrentChange = async (page) => {
    setPaginationData(prev => ({ ...prev, companyCurrentPage: page }));
    const data = await returnCompanyListData(page);
    setCompanyTableData(data);
  };

  const systemCurrentChange = async (page) => {
    setPaginationData(prev => ({ ...prev, systemCurrentPage: page }));
    const data = await returnSystemListData(page);
    setSystemTableData(data);
  };

  const handleSuccess = () => {
    if (activeTab === 'first') {
      fetchCompanyMessageLength();
      fetchCompanyFirstPageList();
    } else if (activeTab === 'second') {
      fetchSystemMessageLength();
      fetchSystemFirstPageList();
    }
  };


  const createMessage = (title) => {
    setOpenModal(true);
    setModalTitle(title)
  };

  const editMessage = (record, title) => {
    setMessageData(record)
    setModalTitle(title)
    setOpenModal(true);
  };

  const deleteMessage = (record) => {
    Modal.confirm({
      title: '确定删除该条数据吗？',
      content: '删除后将无法恢复，请谨慎操作。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await firstDelete(record.id)
        if (res.status === 0) {
          message.success('删除成功')
          if (activeTab === 'first') {
            fetchCompanyMessageLength();
            fetchCompanyFirstPageList();
          } else if (activeTab === 'second') {
            fetchSystemMessageLength();
            fetchSystemFirstPageList();
          }
        }
      }
    })
  };

  const columns = [
    {
      title: '公告主题',
      dataIndex: 'message_title',
      width: 320,
    },
    {
      title: '类别',
      dataIndex: 'message_category',
    },
    {
      title: '发布部门',
      dataIndex: 'message_publish_department',
    },
    {
      title: '发布人',
      dataIndex: 'message_publish_name',
    },
    {
      title: '接收对象',
      dataIndex: 'message_receipt_object',
    },
    {
      title: '公告等级',
      dataIndex: 'message_level',
    },
    {
      title: '发布时间',
      dataIndex: 'message_publish_time',
      render: (text) => <span>{text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''}</span>,
      width: 200,
    },
    {
      title: '最新编辑时间',
      dataIndex: 'message_update_time',
      render: (text) => <span>{text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''}</span>,
      width: 200,
    },
    {
      title: '操作',
      render: (text, row) => (
        <div>
          <Space>
            <a onClick={() => editMessage(row, '编辑公告')}>编辑</a>
            <a style={{ color: 'red' }} onClick={() => deleteMessage(row)}>删除</a>
          </Space>
        </div>
      ),
      width: 200,
      fixed: 'right',
    },
  ];

  const systemColumns = [
    {
      title: '消息主题',
      dataIndex: 'message_title',
    },
    {
      title: '发布者',
      dataIndex: 'message_publish_name',
    },
    {
      title: '发布时间',
      dataIndex: 'message_publish_time',
      render: (text) => <span>{text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''}</span>,
      width: 200,
    },
    {
      title: '操作',
      render: (text, row) => (
        <div>
          <Space>
            <a onClick={() => editMessage(row, '编辑系统消息')}>编辑</a>
            <a style={{ color: 'red' }} onClick={() => deleteMessage(row)}>删除</a>
          </Space>
        </div>
      ),
      width: 200,
      fixed: 'right',
    },
  ];

  return (
    <div className="module-common-wrapped">
      <div className="module-common-content">
        <Tabs activeKey={activeTab} onChange={(key) => setActiveTab(key)}>
          <TabPane tab="公告管理" key="first">
            <div className="pane-content">
              <div className="pane-top">
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                  <div className="search-wrapped">
                    <Select
                      value={department}
                      placeholder="请选择部门"
                      onChange={(value) => setDepartment(value)}
                      onBlur={getListByDepartment}
                      options={[
                        { value: '产品部', label: '产品部' },
                        { value: '用户部', label: '用户部' },
                      ]}
                    >
                    </Select>
                    <Radio.Group
                      value={radioValue}
                      onChange={(e) => {
                        setRadioValue(e.target.value)
                        getMessageListByLevel(e.target.value)
                      }}
                      style={{ marginLeft: 20 }}
                    >
                      <Radio value="一般">一般</Radio>
                      <Radio value="重要">重要</Radio>
                      <Radio value="必要">必要</Radio>
                    </Radio.Group>
                  </div>
                  <div className="button-wrapped">
                    <Button type="primary" style={{ marginRight: 20 }} onClick={fetchCompanyFirstPageList}>全部公告</Button>
                    <Button type="primary" onClick={() => createMessage('发布公告')}>发布公告</Button>
                  </div>
                </div>
                <Table
                  columns={columns}
                  dataSource={companyTableData}
                  pagination={false}
                  rowKey="id"
                  bordered
                  scroll={{ x: 'max-content' }}
                />
              </div>
              <div style={{
                display: 'flex',
                justifyContent: 'flex-end',
                marginTop: 20,
              }}>
                <Pagination
                  current={paginationData.companyCurrentPage}
                  total={paginationData.companyTotal}
                  pageSize={10}
                  onChange={companyCurrentChange}
                  showQuickJumper
                />
              </div>
            </div>
          </TabPane>
          <TabPane tab="系统消息" key="second">
            <div className="pane-content">
              <div className="pane-top">
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
                  <div className="button-wrapped">
                    <Button type="primary" onClick={() => createMessage('发布系统消息')}>发布系统消息</Button>
                  </div>
                </div>
                <Table
                  columns={systemColumns}
                  dataSource={systemTableData}
                  pagination={false}
                  rowKey="id"
                  bordered
                  scroll={{ x: 'max-content' }}
                />
              </div>
              <div style={{
                display: 'flex',
                justifyContent: 'flex-end',
                marginTop: 20,
              }}>
                <Pagination
                  current={paginationData.systemCurrentPage}
                  total={paginationData.systemTotal}
                  pageSize={10}
                  onChange={systemCurrentChange}
                  showQuickJumper
                />
              </div>
            </div>
          </TabPane>
        </Tabs>
      </div>
      <MessageDialog
        visible={openModal}
        formData={messageData}
        title={modalTitle}
        onClose={() => setOpenModal(false)}
        onSuccess={handleSuccess}
      />
    </div>
  );
};

export default MessageManagement;
